<template>
  <PanerForm :isShowBarDrawer="true" :caption="'编辑导航'">
    <template #body>
      <div class="d-row">
        <div class="d-form-group d-form-group-flex d-col-md-6 d-col-xs-12">
          <div class="d-form-label d-text-right">
            <label class="label-text">微应用</label>
          </div>
          <div class="d-form-el">
            <select v-model="state.mid" class="d-form-select">
              <option v-for="item in mappList" :key="item.id" :value="item.id">{{ item.text }}</option>
            </select>
          </div>
        </div>
        <div class="d-form-group d-form-group-flex d-col-md-6 d-col-xs-12">
          <div class="d-form-label d-text-right">
            <label class="label-text">路径</label>
          </div>
          <div class="d-form-el">
            <input v-model="state.path" class="d-form-input" type="text" placeholder="空则为默认菜单" />
          </div>
        </div>
        <div class="d-form-group d-form-group-flex d-col-md-12 d-col-xs-12">
          <div class="d-form-label d-text-right">
            <label class="label-text">菜单</label>
          </div>
          <div class="d-form-el">
            <div style="padding-bottom:8px;">
              <button @click="handleAddItem" class="d-btn d-btn-default d-btn-sm" type="button">添加</button>
            </div>
            <el-tree
              :data="state.meta"
              node-key="id"
              default-expand-all
              @node-drag-start="handleDragStart"
              @node-drag-enter="handleDragEnter"
              @node-drag-leave="handleDragLeave"
              @node-drag-over="handleDragOver"
              @node-drag-end="handleDragEnd"
              @node-drop="handleDrop"
              draggable
              :allow-drop="allowDrop"
              :allow-drag="allowDrag"
              class="form-tree">
              <span class="custom-tree-node" slot-scope="{ data }">
                <span>{{ data.name }}</span>
                <span>
                  <span class="d-text-linker item-action">
                    <i class="el-icon-edit" title="编辑菜单" @click.stop="handleEditItem(data)"></i>
                  </span>
                  <span class="d-text-linker item-action">
                    <i class="el-icon-circle-plus-outline" title="添加子级菜单" @click.stop="handleAddChild(data)"></i>
                  </span>
                  <span class="d-text-linker item-action" title="删除菜单" @click.stop="handleRemoveItem(data)">
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </span>
            </el-tree>
          </div>
        </div>
        <div class="d-form-group d-form-group-flex d-col-md-6 d-col-xs-12">
          <div class="d-form-label d-text-right">
            <label class="label-text">名称</label>
          </div>
          <div class="d-form-el">
            <input v-model="state.name" class="d-form-input" type="text" />
          </div>
        </div>
        <div class="d-form-group d-form-group-flex d-col-md-6 d-col-xs-12">
          <div class="d-form-label d-text-right">
            <label class="label-text">根地址</label>
          </div>
          <div class="d-form-el">
            <input v-model="state.home" class="d-form-input" type="text" />
          </div>
        </div>
        <div class="d-form-group d-form-group-flex d-col-md-6 d-col-xs-12">
          <div class="d-form-label d-text-right">
            <label class="label-text">是否默认</label>
          </div>
          <div class="d-form-el">
            <select v-model="state.isDefault" class="d-form-select">
              <option v-for="item in judgeList" :key="item.id" :value="item.id">{{ item.text }}</option>
            </select>
          </div>
        </div>
        <div class="d-form-group d-form-group-flex d-col-md-6 d-col-xs-12">
          <div class="d-form-label d-text-right">
            <label class="label-text">状态</label>
          </div>
          <div class="d-form-el">
            <select v-model="state.status" class="d-form-select">
              <option v-for="item in statusList" :key="item.id" :value="item.id">{{ item.text }}</option>
            </select>
          </div>
        </div>
        <div class="d-form-group d-form-group-flex d-col-md-6 d-col-xs-12">
          <div class="d-form-label d-text-right">
            <label class="label-text">排序</label>
          </div>
          <div class="d-form-el">
            <input v-model="state.order" class="d-form-input" type="text" placeholder="数值越大越靠前" />
          </div>
        </div>
        <div class="d-form-group d-form-group-flex d-col-md-6 d-col-xs-12">
          <div class="d-form-label d-text-right">
            <label class="label-text">标签</label>
          </div>
          <div class="d-form-el">
            <input v-model="state.labels" class="d-form-input" type="text" />
          </div>
        </div>
      </div>
      <MenuEdit  @onSubmitSuccess="handleEditSuccess" ref="editView" />
      <Dialoger v-model="isShowRelease" :onConfirm="handleSubmitRelease" :dialogCls="'d-paner-sm'" title="发布">
        <template v-slot:body>
          <FormGroup label="版本标题" :col="12">
            <FormInput v-model="releaseName" />
          </FormGroup>
          <FormGroup label="版本描述" :col="12">
            <FormTextarea v-model="releaseDesc" />
          </FormGroup>
        </template>
      </Dialoger>
    </template>
    <template #bar-drawer>
      <button @click="handleSubmit" class="d-btn d-btn-primary" type="button">提交</button>
      <button v-if="isEdit" @click="handleRelease" class="d-btn d-btn-primary" type="button">发布</button>
      <button v-if="!isEdit" @click="handleReset" class="d-btn d-btn-default" type="reset">重置</button>
      <a v-d-goback class="d-btn d-btn-default">返回</a>
    </template>
  </PanerForm>
</template>

<script>
import { PanerForm } from '@daelui/vdog/dist/pages.js'
import { Dialoger, Messager, FormCalendar, FormSelecter, FormGroup, FormInput, FormTextarea } from '@daelui/vdog/dist/components.js'
import { zh as locale } from '@daelui/dogjs/dist/locale.js'
import { objecter, parser, dater, strer } from '@daelui/dogjs/dist/components.js'
import { STATUS } from '@daelui/dogjs/dist/constant.js'
import MenuEdit from './menu-edit.vue'
import navSer from '@/service/action/nav.action'
import vpageSer from '@/service/action/viewpage.action'
import mappSer from '@/service/action/mapp.action.js'
import nrSer from '@/service/action/navrelease.action'
import { state } from '@/service/stock/index.js'

export default {
  components: {
    PanerForm,
    FormCalendar,
    Dialoger,
    FormSelecter,
    FormGroup,
    FormInput,
    FormTextarea,
    MenuEdit
  },

  data () {
    return {
      STATUS,
      isEdit: false, // 是否是编辑模式
      // 表单数据
      state: {
        id: '',
        name: '',
        path: '',
        mid: '',
        isDefault: 1,
        status: 1,
        order: 1,
        meta: [],
        updateTime: '',
        updateUser: '',
        createTime: '',
        createUser: ''
      },
      // 状态列表
      judgeList: state.judgeOptions,
      // 状态列表
      statusList: state.statusList,
      // 页面
      pages: [],
      // 微应用
      mappList: [],
      isShowRelease: false, // 是否显示发布框
      releaseName: '',
      releaseDesc: '', // 发布描述
    }
  },

  watch: {
    'state.mid' () {
      let mapp = this.mappList.find(item => String(item.id) === this.state.mid)
      if (mapp && (!this.state.name || this.mappList.find(item => item.name === this.state.name))) {
        this.state.name = mapp.name
      }
      if (mapp && (!this.state.path || this.mappList.find(item => item.code === this.state.path))) {
        this.state.path = mapp.code
      }
    }
  },

  methods: {
    /**
     * @function 加载数据
    */
    loadItem (id) {
      navSer.queryItem({ id }).then(result => {
        let data = result.data || {}
        data.meta = parser.parse(data.meta)
        data.meta = Array.isArray(data.meta) ? data.meta : []
        this.state = data
      })
    },

    /**
     * @function 提交
    */
    handleSubmit () {
      let defer = null
      let state = objecter.clone(this.state)
      state.meta = parser.stringify(state.meta)
      delete this.state.createTime
      // 编辑
      if (this.isEdit) {
        defer = navSer.editItem(state)
      } else { // 添加
        defer = navSer.addItem(state)
      }
      defer.then(result => {
        if (result.success) {
          Messager.success(locale.action.success)
          // 添加则回到列表页
          if (!this.isEdit) {
            this.$router.push(this.getMicroRoute('/nav/list'))
          }
        } else {
          Messager.danger(locale.action.fail)
        }
      })
    },

    /**
     * @function 重置
    */
    handleReset () {

    },

    // 版本发布
    handleRelease () {
      if (!this.state.id) {
        this.$message({
          message: '需要先保存后再进行发布',
          type: 'warning',
          showClose: true
        })
        return false
      }
      this.releaseDesc = ''
      this.releaseName = dater.format(new Date(), 'yyyy-MM-dd HH:mm:ss'),
      this.isShowRelease = true
    },

    // 发送发布
    handleSubmitRelease () {
      let state = objecter.clone(this.state)
      state.meta = parser.stringify(state.meta)
      nrSer.addItem({
        nid: state.id,
        releaseName: this.releaseName,
        releaseDesc: this.releaseDesc,
        releaseVersion: dater.format(new Date(), 'yyyyMMddHHmmss') + strer.urid(4, false, true),
        name: state.name,
        path: state.path,
        home: state.home,
        meta: state.meta,
        mid: state.mid,
        status: state.status,
        labels: state.labels
      }).then(result => {
        if (result.success) {
          this.$message({
            message: '发布成功',
            type: 'success',
            showClose: true
          })
        } else {
          this.$message({
            message: '发布失败',
            type: 'error',
            showClose: true
          })
        }
      })
    },

    handleDragStart(node, ev) {
      console.log('drag start', node);
    },
    handleDragEnter(draggingNode, dropNode, ev) {
      console.log('tree drag enter: ', dropNode.label);
    },
    handleDragLeave(draggingNode, dropNode, ev) {
      console.log('tree drag leave: ', dropNode.label);
    },
    handleDragOver(draggingNode, dropNode, ev) {
      console.log('tree drag over: ', dropNode.label);
    },
    handleDragEnd(draggingNode, dropNode, dropType, ev) {
      console.log('tree drag end: ', dropNode && dropNode.label, dropType);
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log('tree drop: ', dropNode.label, dropType);
    },
    allowDrop(draggingNode, dropNode, type) {
      return true
    },
    allowDrag(draggingNode) {
      return true
    },

    /**
     * @function 显示与隐藏编辑视图
    */
    showEditView () {
      if (!this.state.mid) {
        this.$message({
          type: 'warning',
          message: '请先选择微应用',
          showClose: true
        })
        return true
      }
      this.editInfo.mid = this.state.mid
      this.$refs.editView.show(this.editInfo)
    },
    /**
     * @function 添加
    */
    handleAddItem (item) {
      this.editInfo = {
        item
      }
      this.showEditView()
    },
    /**
     * @function 添加子节点
    */
    handleAddChild (item) {
      this.editInfo = {
        item,
        parent: true
      }
      this.showEditView()
    },
    /**
     * @function 编辑
    */
    handleEditItem (item) {
      this.editInfo = {
        item,
        edit: true
      }
      this.showEditView()
    },
    /**
     * @function 编辑成功
    */
    handleEditSuccess (data) {
      if (this.editInfo.edit) {
        Object.assign(this.editInfo.item, data)
      } else if (this.editInfo.parent) {
        let node = this.state.meta.find(item => item.id === this.editInfo.item.id)
        if (node) {
          let children = node.children || []
          children.push(data)
          this.$set(node, 'children', children)
        }
      } else {
        this.state.meta.push(data)
      }
    },
    /**
     * @function 删除
    */
    handleRemoveItem (item) {
      this.state.meta = filter(this.state.meta, item)

      // 数据过滤
      function filter (list, item) {
        list = list.filter(node => {
          if (item.id === node.id) {
            return false
          }
          if (node.children) {
            node.children = filter(node.children, item)
          }
          return true
        })
        return list
      }
    }
  },

  beforeMount () {
    let params = this.$route.params
    // 新建
    if (!params.id) {
      this.isEdit = false
    } else { // 编辑
      this.isEdit = true
      this.loadItem(params.id)
    }
  },

  mounted () {
    // 查询页面数据
    vpageSer.queryListAll().then((res) => {
      let list = res.data
      list = Array.isArray(list) ? list : []
      this.pages = list
    })
    // 微应用列表
    mappSer.queryAllListOption().then(list => {
      this.mappList = list
    })
    // 快捷保存
    this.handleQuickSave = (event) => {
      if (event.ctrlKey && event.key === 's') {
        event.preventDefault()
        this.handleSubmit({})
        return false
      }
    }

    // 拦截CTRL+S事件
    document.addEventListener('keydown', this.handleQuickSave)
  },

  beforeDestroy () {
    // 解除CTRL+S事件
    document.removeEventListener('keydown', this.handleQuickSave)
  }
}
</script>

<style scoped>
.d-form-label {
  width: 90px;
}
.form-tree {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.item-action {
  padding: 0 4px;
}
</style>
<style lang="less">
.d-form-product .d-editor-container {
  height: 442px;
  .quill-editor {
    height: 400px
  }
}
.d-form-el .el-select {
  display: block;
}
</style>
